package com.qmo.edu.base;


import android.support.annotation.NonNull;
import android.util.Log;

import com.qmo.edu.base.BaseResponse;
import com.qmo.edu.base.RxBusManager;
import com.qmo.edu.moudle.bean.TokenEvent;
import com.qmo.edu.utils.ExceptionUtil;
import com.qmo.edu.utils.ToastUtils;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
    private static final String TAG = "BaseObserver";

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public final void onNext(BaseResponse<T> tBaseResponse) {
        if (tBaseResponse.getCode() == 200) {
            onSuccess(tBaseResponse.getResult());
        } else {
            onFailure(new Exception(tBaseResponse.getMsg()),
                    tBaseResponse.getCode(),
                    tBaseResponse.getMsg());

        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
        int code = ExceptionUtil.exceptionHandler(e);
        Log.e(TAG, "错误信息---" + e.getMessage() + "-----错误码: " + code);
        String msg = ExceptionUtil.getMsg(code);
        onFailure(e, code, msg);
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(T result);

    private void onFailure(Throwable e, int code, String errorMsg) {
        Log.e(TAG, "onFailure:  什么错误： " + e + "-------错误信息:" + errorMsg);
        ToastUtils.showShortToast(errorMsg);
//        if (code == 1005 || code == 1009) {
//            RxBus.getDefault().post(new TokenEvent());
//        }
        if (code==401){
            RxBusManager.PostToForgetActivity(new TokenEvent());
        }
    }

}
